import java.util.*;

public class Solution {
    public String decodeString(String s) {
        Stack<Object> stack = new Stack<>();
        StringBuilder numSB = new StringBuilder();
        for (char c : s.toCharArray()) {
            if ('0' <= c && c <= '9') {
                numSB.append(c);
            } else if ('a' <= c && c <= 'z') {
                if (!stack.empty() && stack.peek() instanceof String) {
                    String cChar = (String) stack.pop();
                    cChar += c;
                    stack.push(cChar);
                } else {
                    stack.push(String.valueOf(c));
                }
            } else if (c == '[') {
                stack.push(Integer.parseInt(numSB.toString()));
                numSB.delete(0, numSB.length());
            } else if (c == ']') {
                String cChar = (String) stack.pop();
                int repeat = (Integer) stack.pop();
                StringBuilder newChar = new StringBuilder();
                for (int i = 0; i < repeat; i++) {
                    newChar.append(cChar);
                }
                if (!stack.empty() && stack.peek() instanceof String) {
                    String prefix = (String) stack.pop();
                    newChar.insert(0, prefix);
                }
                stack.push(newChar.toString());
            }
        }
        return (String) stack.pop();
    }
}